package com.sqly.doc.base;

import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 袁从斌 on 2019-06-13.
 */
public  abstract class BaseRecyclerViewAdapter<T> extends RecyclerView.Adapter<BaseHolder> {
	private @LayoutRes
    int mItemLayoutId;

	private List<T> mData = null;


	private OnItemClickListener mOnItemClickListener = null;

	public List<T> getData() {
		return mData;
	}

	public void setData(List<T> data) {
		mData = data;
	}

	public void addData(T t,int index){
		mData.add(index,t);
	}

	public void addData(T t){
		mData.add(t);
	}

	public void addAll(List<T> data){
		mData.addAll(data);
	}

	public void clearData(){
		mData.clear();
	}

	public void refreshData(List<T> data){
		clearData();
		addAll(data);
	}

	public BaseRecyclerViewAdapter(int itemLayoutId) {
		mItemLayoutId = itemLayoutId;
		mData = new ArrayList<>();
	}


	public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
		mOnItemClickListener = onItemClickListener;
	}

	@NonNull
	@Override
	public BaseHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
		View view = LayoutInflater.from(parent.getContext()).inflate(mItemLayoutId, parent, false);
		 final BaseHolder holder = new BaseHolder(parent.getContext(),view);
		holder.itemView.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (null!=mOnItemClickListener){
					mOnItemClickListener.onItemClick(holder,
							mData.get(holder.getLayoutPosition()),
							holder.getLayoutPosition());
				}
			}
		});
		return holder;
	}

	@Override
	public void onBindViewHolder(final @NonNull BaseHolder holder, int position) {
		convert(holder,mData.get(position));
	}

	protected abstract void convert(BaseHolder holder, T t);

	@Override
	public int getItemCount() {
		return mData.size();
	}

	public interface OnItemClickListener<T>{
		void onItemClick(BaseHolder view, T t, int position);
	}


}
